﻿using System.Linq;
using Contrib.Taxonomies.Models;
using Orchard.Comments.Models;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;

namespace OrchardHUN.QnA.Services
{
    public class DiscussionsService : IDiscussionsService
    {
        private readonly IContentManager _contentManager;

        public DiscussionsService(IContentManager contentManager)
        {
            _contentManager = contentManager;
        }

        public IContent New(int discussionPoolId)
        {
            var discussion = _contentManager.New("QnADiscussion");

            // This way the discussion's path will contain also the url of the taxonomy.
            discussion.As<CommonPart>().Container = _contentManager.Get<CommonPart>(discussionPoolId).Container;

            return discussion;
        }

        public IContent Create(IContent discussion)
        {
            // So that the discussion's url will contain the taxonomy's path.
            // Also this is to ensure that functionality that depends on the container-containable relationship works
            // as expected (this way discussions are "under" the QnA taxonomy).
            // Useful for breadcrumbs, for example.
            var taxonomy = _contentManager.Query<TaxonomyPart, TaxonomyPartRecord>().Where(tax => tax.TermTypeName == "QnADiscussionPool").List().FirstOrDefault();
            discussion.As<CommonPart>().Container = taxonomy.ContentItem;

            var commentsPart = discussion.As<CommentsPart>();
            commentsPart.CommentsActive = commentsPart.CommentsShown = true;

            _contentManager.Create(discussion);
            
            return discussion;
        }
    }
}